package org.zjx.core;

import lombok.Data;
import org.zjx.log.LogLevel;
import org.zjx.log.Logger;
@Data
//子线程能继承父线程的实例
public class GameInstance {
    private final Logger logger = Logger.getLogger();


    private final GameThread gameThread;

    private GameContext gameContext;


    // ThreadLocal存储
    private static final InheritableThreadLocal<GameInstance> threadLocalInstance =
            new InheritableThreadLocal<>();

    // 私有构造方法
    private GameInstance(GameThread gameThread, GameContext gameContext) {
        this.gameThread = gameThread;
        this.gameContext = gameContext;
    }

    /**
     * Builder类用于初始化实例
     */
    public static class Builder {
        private GameThread gameThread;
        private GameContext gameContext;

        public Builder gameThread(GameThread gameThread) {
            this.gameThread = gameThread;
            return this;
        }

        public Builder gameContext(GameContext gameContext) {
            this.gameContext = gameContext;
            return this;
        }
        /**
         * 构建并设置当前线程的实例
         */
        public void build() {
            threadLocalInstance.set(new GameInstance(gameThread, gameContext));
        }

        /**
         * 构建并设置指定线程的实例（高级用法）
         */
        public void buildForThread(Thread thread) {
            final GameInstance instance = new GameInstance(gameThread, gameContext);
            threadLocalInstance.set(instance);
        }
    }

    /**
     * 获取当前线程的实例
     *
     * @throws IllegalStateException 如果实例未初始化
     */
    public static GameInstance getInstance() {
        GameInstance instance = threadLocalInstance.get();
        if (instance == null) {
            throw new IllegalStateException("OperateInstance not initialized. Please call Builder.build() first.");
        }
        return instance;
    }

    /**
     * 安全获取当前线程的实例，如果未初始化则返回null
     */
    public static GameInstance getInstanceIfPresent() {
        return threadLocalInstance.get();
    }

    /**
     * 执行操作
     */
    public void doSomething() {
        logger.log("GameModule", LogLevel.INFO, Thread.currentThread().getName() );
    }

    /**
     * 清理当前线程的实例
     */
    public static void remove() {
        threadLocalInstance.remove();
    }

    /**
     * 重新配置当前线程的实例
     */
    public static void reconfigure() {
        GameInstance current = threadLocalInstance.get();
        if (current != null) {
            threadLocalInstance.set(new GameInstance(current.gameThread, current.gameContext));
        }
    }
}